<?php
session_start();

$servername = "localhost";
$username = "root";
$password = "123456";
$dbname = "userdb";

// 创建连接
$conn = new mysqli($servername, $username, $password, $dbname);

// 检测连接
if ($conn->connect_error) {
    die("连接失败: " . $conn->connect_error);
}

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $username = $_POST['regUsername'];
    $password = $_POST['regPassword'];
    $confirm_password = $_POST['confirmPassword'];
    // 验证用户名不为空
    echo "接收到的用户名: " . htmlspecialchars($username) . "<br>";
    if (empty($username)) {
        die("用户名不能为空");
    }

    // 验证密码与确认密码是否匹配
    if ($_POST['password'] !== $_POST['confirm_password']) {
        die("密码不匹配");
    }

    // 创建密码哈希
    $hashed_password = password_hash($password, PASSWORD_DEFAULT);

    // 插入新用户
    // 插入新用户
    $sql = "SELECT COUNT(*) AS count FROM users WHERE username = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("s", $username);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($result->fetch_assoc()['count'] > 0) {
        die("该用户名已存在");
    }
if (!$stmt->execute()) { // 改为检查执行是否失败
    $error = $stmt->error; // 获取预处理语句的错误信息
    echo "注册失败: " . htmlspecialchars($error); // 输出错误信息，并使用htmlspecialchars防止XSS攻击
} else {
    echo "用户注册成功";
}

$stmt->close();
}

$conn->close();
?>